<?php
namespace Common\Mysql;
class TemplateMysql extends CommonMysql {

    public function addTemplate($data) {
        $title = v($data,'title');
        verify($title,'notEmpty','模板标题不能为空');


        $code = v($data,'code');
        verify($code,'notEmpty','模板路径不能为空');

        $status = v($data,'status',1,true);
        verify($status,'isStatus','非法状态');

        if($this->where("`title`='{$title}' OR `code` = '{$code}'")->count()) {
            E('模板已经存在');
        }

        $imageInfo = uploadImage('cover','cover');

        $cover = v($imageInfo,'path');
        verify($cover,'notEmpty','模板封面不能为空');

        $id = $this->addRecord(array(
            'title'     =>  $title,
            'cover'     =>  $cover,
            'code'      =>  $code,
            'createtime'=>  NOW_TIME,
            'status'    =>  $status,
        ),false,'模板添加失败');

        return $id;
    }

    public function updateTemplate($data) {
        $id = v($data,'id');
        verify($id,'notEmpty','模板ID不能为空');
        verify($id,'isID','非法模板ID');

        $title = v($data,'title');
        verify($title,'notEmpty','模板标题不能为空');

        $code = v($data,'code');
        verify($code,'notEmpty','模板路径不能为空');

        $status = v($data,'status',1,true);
        verify($status,'isStatus','非法状态');

        if($this->where("(`title`='{$title}' OR `code` = '{$code}') AND `id` <> {$id}")->count()) {
            E('模板已经存在');
        }

        $update_data = array(
            'id'        =>  $id,
            'title'     =>  $title,
            'code'      =>  $code,
            'status'    =>  $status,
        );

        if($_FILES['cover']['tmp_name']) {
            $imageInfo = uploadImage('cover','cover');
            if($imageInfo) {
                $update_data['cover'] = v($imageInfo,'path');
            }
        } 

        $id = $this->updateRecord($update_data,false,'模板添加失败');

        return $id;
    }

}
?>
